package com.fishery.refrigeratory.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import com.fishery.refrigeratory.client.BaseClient;
import com.fishery.refrigeratory.client.OrderClient;
import com.fishery.refrigeratory.entity.Refrigeratory;
import com.fishery.refrigeratory.entity.RefrigeratoryInInfo;
import com.fishery.refrigeratory.entity.RefrigeratoryOutInfo;
import com.fishery.refrigeratory.entity.RefrigeratoryPrepareEnter;
import com.fishery.refrigeratory.entity.vo.OrderAndProductVo;
import com.fishery.refrigeratory.entity.vo.OrderVo;
import com.fishery.refrigeratory.entity.vo.RefrigeratoryInfoVo;
import com.fishery.refrigeratory.entity.vo.SourceInfoVo;
import com.fishery.refrigeratory.service.RefrigeratoryInInfoService;
import com.fishery.refrigeratory.service.RefrigeratoryOutInfoService;
import com.fishery.refrigeratory.service.RefrigeratoryPrepareEnterService;
import com.fishery.refrigeratory.service.RefrigeratoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wgz
 * @since 2021-2-2
 */
@Api(description = "冷库出库信息接口")
@RestController
@CrossOrigin
@RequestMapping("/refrigeratoryOutInfo")
public class RefrigeratoryOutInfoController {

    @Autowired
    private RefrigeratoryOutInfoService refrigeratoryOutInfoService;

    @Autowired
    private RefrigeratoryInInfoService refrigeratoryInInfoService;

    @Autowired
    private RefrigeratoryService refrigeratoryService;

    @Autowired
    private RefrigeratoryPrepareEnterService refrigeratoryPrepareEnterService;


    /**
     * 新增出库信息
     *
     * @param orderVo
     * @return
     */
    @ApiOperation(value = "新增出库信息")
    @PostMapping("/in")
    public Result saveRefrigeratoryOutInfo(@RequestBody @ApiParam(value = "出库信息对象", required = true) OrderVo orderVo) {
        if (orderVo == null
            ||StringUtils.isEmpty(orderVo.getProductId())
            || StringUtils.isEmpty(orderVo.getTargetId())
            || StringUtils.isEmpty(orderVo.getLogisticsId())
            || StringUtils.isEmpty(orderVo.getTargetName())
            || StringUtils.isEmpty(orderVo.getProductName())
            || StringUtils.isEmpty(orderVo.getBaseId())
            || StringUtils.isEmpty(orderVo.getWeight())
            || StringUtils.isEmpty(orderVo.getReceiveAddress())
            || StringUtils.isEmpty(orderVo.getAddressLongitude())
            || StringUtils.isEmpty(orderVo.getAddressLatitude())
            || StringUtils.isEmpty(orderVo.getPhoneNumber())
            || StringUtils.isEmpty(orderVo.getMoney())
            || StringUtils.isEmpty(orderVo.getAmount())
            || StringUtils.isEmpty(orderVo.getSourceType())
            || StringUtils.isEmpty(orderVo.getTargetType())
        ) {
           return Result.error();
        }
        RefrigeratoryOutInfo refrigeratoryOutInfo = new RefrigeratoryOutInfo();
        refrigeratoryOutInfo.setRefrigeratoryId(orderVo.getTargetId());
        refrigeratoryOutInfo.setProductName(orderVo.getProductName());
//        refrigeratoryOutInfo.set
        return refrigeratoryOutInfoService.insertOutInfo(refrigeratoryOutInfo) != 0 ? Result.success("创建成功") : Result.error("创建失败");
    }

    /**
     * 根据出库编号id删除出库信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据出库编号id删除出库信息")
    @DeleteMapping("/in/{id}")
    public Result deleteRefrigeratoryOutInfoById(@PathVariable(value = "id", required = true) @ApiParam(value = "出库编号id") String id) {
        if (id == null) {
            return Result.error();
        }
        return refrigeratoryOutInfoService.deleteOutIno(id) != 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    /**
     * 修改出库信息
     *
     * @param refrigeratoryOutInfo
     * @return
     */
    @ApiOperation(value = "修改出库信息")
    @PutMapping("/in")
    public Result updateRefrigeratoryOutInfo(@RequestBody @ApiParam(value = "出库信息对象", required = true) RefrigeratoryOutInfo refrigeratoryOutInfo) {
        if (refrigeratoryOutInfo == null
                ||StringUtils.isEmpty(refrigeratoryOutInfo.getRefrigeratoryId())
                || StringUtils.isEmpty(refrigeratoryOutInfo.getProductName())
                || StringUtils.isEmpty(refrigeratoryOutInfo.getRefrigeratoryInId())
                || StringUtils.isEmpty(refrigeratoryOutInfo.getRefrigeratoryOutCapacity())
                || StringUtils.isEmpty(refrigeratoryOutInfo.getWarehousingPersonId())
        ) {
            return Result.error();
        } else if (refrigeratoryOutInfo.getRefrigeratoryOutCapacity() < 0) {
            return Result.error();
        }
        return refrigeratoryOutInfoService.updateOutInfo(refrigeratoryOutInfo) != 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

//    /**
//     * 通过冷库入库编号id查看该批次的出库信息（为了溯源,查看当前订单分批流向的出库信息）
//     *
//     * @param id
//     * @return
//     */
//    @ApiOperation(value = "通过冷库入库编号id查看该编号的出库信息（溯源）")
//    @GetMapping("/selectInfoByrefrigeratoryInId/{id}")
//    public Result selectInfoByrefrigeratoryInId(@PathVariable(value = "id", required = true) @ApiParam(value = "入库编号id", required = true) String id) {
//        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectInfoByrefrigeratoryInId(id));
//    }

//    /**
//     * 通过冷库出库编号id查看该编号对应的入库编号（溯源）
//     *
//     * @param id
//     * @return
//     */
//    @ApiOperation(value = "通过冷库出库编号id查看该编号对应的入库编号（溯源）")
//    @GetMapping("/selectInfoByrefrigeratoryOutId/{id}")
//    public Result selectInfoByrefrigeratoryOutId(@PathVariable(value = "id", required = true) @ApiParam(value = "出库编号id", required = true) String id) {
//        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectInfoByrefrigeratoryOutId(id).getRefrigeratoryInId());
//    }

    /**
     * 根据出库编号id查询出库信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据出库编号id查询出库信息")
    @GetMapping("/in/{id}")
    public Result selectRefrigeratoryById(@PathVariable(value = "id", required = true) @ApiParam(value = "出库编号id", required = true) String id) {
        return Result.success("查询成功").data(refrigeratoryOutInfoService.getById(id));
    }

    /**
     * 根据冷库id查询冷库的出库信息
     *
     * @param RefrigeratoryId
     * @return
     */
    @ApiOperation(value = "根据冷库id查询冷库的出库信息")
    @GetMapping("/selectInfoByRefrigeratoryId/{id}")
    public Result selectInfoByRefrigeratoryId(@PathVariable(value = "id", required = true) @ApiParam(value = "冷库id", required = true) String RefrigeratoryId) {
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectInfoBytRefrigeratoryId(RefrigeratoryId));
    }

    /**
     * 根据冷库id分页查询冷库的出库信息
     *
     * @param refrigeratoryId
     * @return
     */
    @ApiOperation(value = "根据冷库id分页查询冷库的出库信息")
    @GetMapping("/selectPageInfoByRefrigeratoryId/{id}/{page}/{size}")
    public Result selectPageInfoByRefrigeratoryId(@PathVariable(value = "id", required = true) @ApiParam(value = "冷库id", required = true) String refrigeratoryId,
                                                  @PathVariable(value = "page", required = true) @ApiParam(value = "页数", required = true) Integer page,
                                                  @PathVariable(value = "size", required = true) @ApiParam(value = "行数", required = true) Integer size) {
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 1 : size;
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectPageInfoByRefrigeratoryId(refrigeratoryId, page, size));
    }

    /**
     * 根据基地id查询冷库的出库信息
     *
     * @param baseId
     * @return
     */
    @ApiOperation(value = "根据基地id查询冷库的出库信息")
    @GetMapping("/selectInfoByBaseId/{id}")
    public Result selectInfoByBaseId(@PathVariable(value = "id", required = true) @ApiParam(value = "基地id", required = true) String baseId) {
        List<Refrigeratory> refrigeratoryList = refrigeratoryService.getRefrigeratoryByBaseId(baseId);
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectInfoByBaseId(refrigeratoryList));
    }

    /**
     * 根据基地id分页查询冷库的出库信息
     * @param baseId
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "根据基地id分页查询冷库的出库信息")
    @GetMapping("/selectPageInfoByBaseId/{id}/{page}/{size}")
    public Result selectPageInfoByBaseId(@PathVariable(value = "id", required = true) @ApiParam(value = "基地id", required = true) String baseId,
                                         @PathVariable(value = "page", required = true) @ApiParam(value = "页数", required = true) Integer page,
                                         @PathVariable(value = "size", required = true) @ApiParam(value = "行数", required = true) Integer size) {
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 1 : size;
        List<Refrigeratory> refrigeratoryList = refrigeratoryService.getRefrigeratoryByBaseId(baseId);
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectPageInfoByBaseId(refrigeratoryList, page, size));
    }

    /**
     * 查询所有出库信息（不限于基地和冷库）
     *
     * @return
     */
    @ApiOperation(value = "查询所有出库信息（不限于基地和冷库）")
    @GetMapping("/selectAllInfo")
    public Result selectAllInfo() {
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectAllInfo());
    }

    /**
     * 分页查询所有出库信息（不限于基地和冷库）
     *
     * @return
     */
    @ApiOperation(value = "分页查询所有出库信息（不限于基地和冷库）")
    @GetMapping("/selectAllInfo/{page}/{size}")
    public Result selectPageAllInfo(@PathVariable(value = "page") @ApiParam(value = "页数") Integer page,
                                    @PathVariable(value = "size") @ApiParam(value = "行数") Integer size) {
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 1 : size;
        return Result.success("查询成功").data(refrigeratoryOutInfoService.selectPageAllInfo(page, size));
    }

//    /**
//     * 取消订单删除出库接口
//     *
//     * @param refrigeratoryOutId
//     * @return
//     */
//    @DeleteMapping("/order/{refrigeratoryOutId}")
//    @ApiOperation("取消订单对应删除出库接口")
//    public Result deleteOrder(@PathVariable(value = "refrigeratoryOutId") String refrigeratoryOutId) {
//        return refrigeratoryOutInfoService.deleteOutIno(refrigeratoryOutId) != 0 ? Result.success("取消成功") : Result.error("取消失败");
//    }

//    /**
//     * 创建订单
//     *
//     * @param orderAndProductVo
//     * @return
//     */
//    @PostMapping("/order")
//    @ApiOperation("创建订单时对应创建出库接口")
//    public Result createOrder(@RequestBody @ApiParam("订单与出库对象") OrderAndProductVo orderAndProductVo) {
//        if (orderAndProductVo == null) {
//            return Result.error("请输入正确信息!");
//        }
//        //得到入库信息
//        RefrigeratoryInInfo InRefrigeratory = refrigeratoryInInfoService.getById(orderAndProductVo.getRefrigeratoryInId());
//        if (InRefrigeratory == null) {
//            return Result.error("改商品没有库存！");
//        }
//        //如果冷库不存在则退出
//        Refrigeratory refrigeratory = refrigeratoryService.getById(InRefrigeratory.getRefrigeratoryId());
//        if (refrigeratory == null) {
//            return Result.error("改商品没有库存！");
//        }
//        //获得当前冷库已用容量
//        int AllUsedCapacity = refrigeratory.getRefrigeratoryUsedCapacity();
//        //当前输出容量
//        int OutCapacity = (int) (orderAndProductVo.getAmount() * orderAndProductVo.getWeight());
//        //得到当前入库信息总容量
//        Integer InCapacity = InRefrigeratory.getRefrigeratoryInCapacity();
//        //得到当前入库信息已使用容量
//        Integer InUsedCapacity = InRefrigeratory.getRefrigeratoryInUsedCapacity();
//        //剩余容量
//        Integer surplus = InCapacity - InUsedCapacity;
//        if (InUsedCapacity + OutCapacity > InCapacity) {
//            throw new GlobalException(StatusCode.ERROR, "创建订单失败！！！当前容量不足，只剩余" + surplus + "kg的容量");
//        }
//        return refrigeratoryOutInfoService.createOrder(orderAndProductVo) ? Result.success("创建成功") : Result.error("创建失败,请检查信息是否完整！");
//    }


    /**
     * 根据产品编号溯源接口
     *
     * @param id
     * @return
     */
    @GetMapping("/getProduct/{id}")
    @ApiOperation("根据产品编号溯源接口")
    public Result getProduct(@PathVariable(value = "id", required = true) @ApiParam(value = "产品编号", required = true) String id) {
        if (id == null) {
            return Result.error();
        }
        //先获取出库信息
        RefrigeratoryOutInfo refrigeratoryOutInfo = refrigeratoryOutInfoService.getById(id);
        //获取冷库信息
        Refrigeratory refrigeratory = refrigeratoryService.getById(refrigeratoryOutInfo.getRefrigeratoryId());
        //获取入库信息
        RefrigeratoryInInfo refrigeratoryInInfo = refrigeratoryInInfoService.getById(refrigeratoryOutInfo.getRefrigeratoryInId());
        SourceInfoVo sourceInfoVo = new SourceInfoVo();
        sourceInfoVo.setRefrigeratoryInTime(refrigeratoryInInfo.getGmtCreate());
        sourceInfoVo.setRefrigeratoryName(refrigeratory.getRefrigeratoryName());
        sourceInfoVo.setRefrigeratoryOutTime(refrigeratoryOutInfo.getGmtModified());
        sourceInfoVo.setWarehousingInPersonId(refrigeratoryInInfo.getWarehousingPersonId());
        sourceInfoVo.setWarehousingOutPersonId(refrigeratoryOutInfo.getWarehousingPersonId());
        //获得入库名
        sourceInfoVo.setBaseName(refrigeratoryPrepareEnterService.getRefrigeratoryEnterByProductId(id));
//        Result baseInfo = baseClient.getBaseInfo(refrigeratory.getBaseId());
//        if (baseInfo.getStatusCode() == 20001) {
//            return Result.error("查询基地名失败");
//        }
//        Object data = baseInfo.getData();
//        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(data));
//        sourceInfoVo.setBaseName(jsonObject.getString("name"));
        return Result.success().data(sourceInfoVo);
    }
//
//    /**
//     * 创建订单后调用库存
//     *
//     * @param orderVo
//     * @return
//     */
//    @PostMapping("/createOutInfo")
//    @ApiOperation("创建订单后调用库存")
//    public Result createOutInfo(@RequestBody OrderVo orderVo) {
//        if (orderVo == null) {
//            return Result.error("请输入正确信息!");
//        }
//        return Result.success().data(refrigeratoryOutInfoService.createOutInfo(orderVo));
//    }
}